const router = require('koa-router')()
const upload = require('../upload')
const mongoose = require('mongoose')
const funs = require('../lib/funs')

const Image = mongoose.model('Image')
const User = mongoose.model('User')
const Comments = mongoose.model('Comment')

router.prefix('/images')

router.post('/', upload.single('imgfile'), async function (ctx) {
    const {
        title,
        description
    } = ctx.req.body
    const {
        originalname,
        mimetype,
        filename: diskfilename
    } = ctx.req.file
    const doc = await Image.create({
        title,
        uploader_id: ctx.session.userId,
        description,
        originalname,
        mimetype,
        diskfilename,
    })
    ctx.redirect(`/images/${doc._id}`)
})

router.get('/:imageid', async ctx => {
    const leastCom = await Comments.find({})
    .sort({createdAt: -1}).limit(3)
    
    const image = await Image.findByIdAndUpdate(
        ctx.params.imageid,
        {$inc: { viewtimes: 1 }},
        {new: true}
        )
    const uploaders = await User.find(
            {_id: image.uploader_id},
            {username: 1, nickname: 1}
        )
    const uploader = uploaders[0]
        console.log(uploader)
    const comments = await Comments.find({
            image: ctx.params.imageid
        })
        .sort({
            createdAt: -1
        }).limit(5)
    const info = await funs()
    if (image) {
        await ctx.render('show', {
            image,
            comments,
            info,
            uploader,
            username: ctx.session.username,
            nickname: ctx.session.nickname,
            userId: ctx.session.userId,
            leastCom
        })
    }
})

router.post('/likes/:imageid', async ctx => {
    const infos = await Image.aggregate().group(
        {
            _id: null,
            numOfLikes: {$sum: "$likes"},
        }
    )
    const info = infos[0]
    const doc = await Image.findByIdAndUpdate(
        ctx.params.imageid, 
        {
            $inc: {
                likes: 1
            }
        }, 
        {
            new: true
        }
    )
    ctx.body = {
        doc,
        info
    }
})

module.exports = router